import * as UserService from '../service/userService'

export default {
    namespace: 'user',
    state: {
        data: [],
        map: {},
        loading: false,
    },
    reducers: {
        userList(state, {paylod}) {
            console.log(paylod);

            let newData = []
            let newMap = {}

            const newState = paylod.reduce((res, item, index) => {
                res.data.push(item)
                res.map[item.id] = index
                return res
            }, {
                data: newData,
                map: newMap
            })

            return {
                ...state,
                ...newState
            }
        },
        isLoading(state, { payload }) {
            return {
                ...state,
                loading: payload,
            }
        }
    },
    effects: {
        // 曾删改查
        *add(action, { call, put }) {
            const { payload } = action
            yield put({ type: 'isLoading', payload: true })
            yield call(UserService.add, payload);
            yield put({ type: 'get' })
            yield put({ type: 'isLoading', payload: false })
        },
        *del(action, { call, put }) {
            const { payload } = action
            yield put({ type: 'isLoading', payload: true })
            yield call(UserService.del, payload);
            yield put({ type: 'get' })
            yield put({ type: 'isLoading', payload: false })
        },
        *update(action, { call, put }) {
            const { payload } = action
            yield put({ type: 'isLoading', payload: true })
            yield call(UserService.update, payload);
            yield put({ type: 'get' })
            yield put({ type: 'isLoading', payload: false })
        },
        *get(action, { call, put }) {
            yield put({ type: 'isLoading', payload: true })
            let res = yield call(UserService.get)
            yield put({ type: 'userList', paylod: res.data })
            yield put({ type: 'isLoading', payload: false })
        },
    }
}